package Search;

import Data.MassageData;
import Data.MassageListData;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;

public class SearchMassageFromGroup {
    String url = "jdbc:mysql://127.0.0.1:3306/nox?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
    String user = "root";
    String password = "Mi20030610.";
    String sql = "SELECT *FROM massagelist WHERE receiver_id=? ORDER BY date DESC limit 20 OFFSET ?;";

    private MassageData massageData;

    public SearchMassageFromGroup(MassageData massageData) {
        this.massageData = massageData;
    }

    public MassageData getMassageData() {
        return massageData;
    }

    public void setMassageData(MassageData massageData) {
        this.massageData = massageData;
    }

    public MassageListData searchMassage() throws ClassNotFoundException, SQLException {
        ArrayList<MassageData> massagelist=new ArrayList<>();
        MassageListData res=new MassageListData();
        res.setReceiver_id(massageData.getReceiver());
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection Conn = DriverManager.getConnection(url, user, password);

        PreparedStatement operation=Conn.prepareStatement(sql);
        operation.setString(1,massageData.getReceiver());
        operation.setInt(2,massageData.getSum());

        ResultSet resultSet=operation.executeQuery();
        while(resultSet.next())
        {
            MassageData e=new MassageData();
            e.setSender(resultSet.getString("sender_id"));
            e.setReceiver(resultSet.getString("receiver_id"));
            e.setTimestamp(resultSet.getTimestamp("date"));
            e.setContent(resultSet.getString("content"));
            int is_file=resultSet.getInt("is_file");
            if(is_file==1)
            {
                e.setIs_file(1);
                e.setFile_id(resultSet.getString("file_id"));
                e.setFile_name(resultSet.getString("file_name"));
            }
            else e.setIs_file(0);
            System.out.println("找到了"+e.getSender()+"to "+e.getReceiver()+" "+e.getIs_file());
            massagelist.add(e);
        }
        resultSet.close();
        operation.close();
        Conn.close();
        Collections.reverse(massagelist);
        res.setMassagelist(massagelist);
        return res;
    }

}
